import NProgress from 'nprogress'
import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import { useUserStore } from './stores/auth'

export enum Route {
  ROOT = 'ROOT',
  LOGIN = 'LOGIN',
  NOT_FOUND = 'NOT_FOUND',
  CHAPTER = 'CHAPTER',
  REPORT = 'REPORT',
  CLASSSTEP = 'CLASSSTEP',
  DETAIL = 'DETAIL',
  MAIN = 'MAIN',
  ABOUTUS = 'ABOUTUS',
  COMPETITION = 'COMPETITION',
  WAITING = 'WAITING'
}

// const publicRoutes: Route[] = Object.values(Route);
const publicRoutes: Route[] = [Route.LOGIN, Route.NOT_FOUND]

export const history = createWebHistory()

export const routes: RouteRecordRaw[] = [
  {
    path: '',
    name: Route.ROOT,
    redirect: { name: Route.MAIN }
  },
  {
    path: '/main',
    component: () => import('@/layouts/themes/main.vue'),
    redirect: { name: Route.MAIN },
    children: [
      {
        path: 'competition',
        name: Route.COMPETITION,
        component: () => import('@/views/competition.vue')
      },
      {
        path: '',
        name: Route.MAIN,
        component: () => import('@/views/main.vue')
      },
      {
        path: 'helper',
        name: Route.ABOUTUS,
        component: () => import('@/views/helper.vue')
      },
      {
        path: 'detail',
        name: Route.DETAIL,
        component: () => import('@/views/details.vue')
      }
    ]
  },

  {
    path: '/chapter',
    component: () => import('@/layouts/themes/details.vue'),
    redirect: { name: Route.CHAPTER },
    children: [
      {
        path: '',
        name: Route.CHAPTER,
        component: () => import('@/views/chapter')
      }
    ]
  },

  {
    path: '/login',
    component: () => import('@/layouts/themes/authorization.vue'),
    redirect: { name: Route.LOGIN },
    children: [
      {
        path: '',
        name: Route.LOGIN,
        component: () => import('@/views/Login')
      }
    ]
  },

  {
    path: '/waiting',
    name: Route.WAITING,
    component: () => import('@/views/waiting.vue')
  },
  {
    path: '/:path(.*)',
    name: Route.NOT_FOUND,
    component: () => import('@/views/404.vue')
  }
]

export const router = createRouter({
  history,
  routes,
  scrollBehavior(_, __) {
    return { top: 0 }
  }
})

router.beforeEach((to, _from, next) => {
  NProgress.start()

  const userStore = useUserStore()
  if (to.name === Route.LOGIN && userStore.authenticated) {
    next({ name: Route.MAIN })
  } else {
    if (publicRoutes.includes(to.name as Route) || userStore.authenticated) {
      next()
    } else {
      next({ name: Route.LOGIN })
    }
  }
})

router.afterEach(() => {
  setTimeout(() => NProgress.done(), 200)
})
